import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { Repository } from "typeorm";
import { OrderInfoEntity } from "../entity/info";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { ProductInfoEntity } from "../../product/entity/info";
import { Utils } from "../../../comm/utils";
import { CreateOrderDTO } from "../dto/info";
import { PluginService } from "../../plugin/service/info";
import { Context } from "@midwayjs/koa";
import { UserInfoEntity } from "../../user/entity/info";
import { UserWxService } from "../../user/service/wx";
import { ProductItemEntity } from "../../product/entity/item";



@Provide()
export class OrderInfoService extends BaseService {
    @InjectEntityModel(OrderInfoEntity)
    orderInfoModel: Repository<OrderInfoEntity>

    @InjectEntityModel(UserInfoEntity)
    userInfoModel: Repository<UserInfoEntity>

    @InjectEntityModel(ProductItemEntity)
    productItemModel: Repository<ProductItemEntity>


    @InjectEntityModel(ProductInfoEntity)
    productInfoModel: Repository<ProductInfoEntity>

    @Inject()
    userWxService: UserWxService

    @Inject()
    pluginService: PluginService

    @Inject()
    utils: Utils

    @Inject()
    ctx: Context

    // 后台下单，分享至用户进行支付
    async supportOrder(param: any) {
    }



    // 用户下单，支持商品订单和服务订单
    async createOrder(param: CreateOrderDTO, userId: number) {

        if (!userId) {
            throw new CoolCommException('用户ID不能为空');
        }

        const user = await this.userInfoModel.findOneBy({ id: userId });
        if (!user) {
            throw new CoolCommException('用户不存在');
        }


        const openid = await this.userWxService.getOpenid(userId);
        if (!openid) {
            throw new CoolCommException('用户未绑定微信');
        }
        const { productItemId, remark } = param;

        const productItem = await this.productItemModel.findOne({ where: { id: productItemId } })
        if (!productItem) {
            throw new CoolCommException('产品项不存在');
        }
        const price = await this.computedOrderPrice(productItemId);

        // 生成订单号
        const orderNum = await this.pluginService.invoke('pay-wx', 'createOrderNum');


        const order = await this.orderInfoModel.save({
            orderNo: orderNum,
            type: 'product',
            price: price,
            status: 0,
            userId: userId,
            remark: remark,
        })

        // 获得微信支付 SDK 实例
        const wxPayInstance = await this.pluginService.invoke('pay-wx', 'getInstance');
        const payWxConfig = await this.pluginService.getConfig('pay-wx');


        const params = {
            description: productItem.name,
            out_trade_no: order.orderNo,
            notify_url: payWxConfig?.notifyUrl || '回调url',
            amount: {
                total: this.utils.mul(price, 100),
            },
            payer: {
                openid: openid,
            },
            scene_info: {
                payer_client_ip: this.ctx.ip || '127.0.0.1',
            },
        };
        try {
            const result = await wxPayInstance.transactions_jsapi(params)
            return result;
        } catch (e) {
            throw new CoolCommException(`微信下单失败: ${e?.message || e}`);
        }

    }

    // 计算订单价格
    async computedOrderPrice(productItemId: number) {
        const productItem = await this.productItemModel.findOne({ where: { id: productItemId } });
        if (!productItem) {
            throw new CoolCommException('产品项不存在');
        }
        // 计算订单价格
        let price = productItem.price;

        return price;
    }
}